﻿using MimeKit;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using Microsoft.Extensions.Options;
using MimeKit.Text;
using Tiens.NotificationHub.Core.Options;
using Tiens.NotificationHub.IntegrationEvents;
using Tiens.NotificationHub.Services;
using MailKit.Security;

namespace Tiens.NotificationHub.Core.Services
{
    public class SmtpMailService : ISmtpMailService
    {
        private readonly IOptions<SmtpOptions> _smtpOptions;

        public SmtpMailService(IOptions<SmtpOptions> smtpOptions)
        {
            _smtpOptions = smtpOptions;
        }

        public Task SendTextMessageAsync(MailAddress fromAddress, IEnumerable<MailAddress> toAddress, string subject,
            string body)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(fromAddress.Name, fromAddress.ToString()));
            message.To.AddRange(toAddress.Select(x => new MailboxAddress(x.Name, x.Address)));
            message.Subject = subject;
            message.Body = new TextPart(TextFormat.Plain) {Text = body};

            using (var client = new SmtpClient())
            {
                client.ServerCertificateValidationCallback = (s, c, h, e) => true;
                client.Connect(_smtpOptions.Value.Host, _smtpOptions.Value.Port, SecureSocketOptions.None);
                client.AuthenticationMechanisms.Remove("XOAUTH2");

                // Note: only needed if the SMTP server requires authentication
                client.Authenticate(_smtpOptions.Value.UserName, _smtpOptions.Value.Password);

                client.Send(message);

                client.Disconnect(true);
            }

            return Task.CompletedTask;
        }

    }
}
